from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session, Session
from app.config.db import DbConfig
from .singleton import Singleton
class DbUtils(object):
    """
    DbUtils DB工具类
    :version: 1.4
    :date: 2020-02-11
    """

    sess: Session = None
    default_config: DbConfig = None

    def __init__(self, config: DbConfig = None):
        if not config:
            config = self.default_config

        self.sess = self._create_scoped_session(config)

    def __del__(self):
        self.sess.close()

    @staticmethod
    def _create_scoped_session(config: DbConfig):
        
        engine = create_engine(
            config.get_url(),
            pool_size=config.pool_size,
            max_overflow=config.max_overflow,
            pool_recycle=config.pool_recycle,
            echo=config.echo,
            isolation_level="AUTOCOMMIT"
        )
        session = scoped_session(sessionmaker(autoflush=True, bind=engine))
        return session

    # 根据文件获取SQL文件
    @staticmethod
    def get_sql_by_file(file_path, params={}):
        sql = DbUtils._get_file(file_path)
        return sql.format(**params)

    # 获取SQL文件
    @staticmethod
    def _get_file(file_path):
        with open('app/sql/' + file_path, 'r', encoding='utf-8') as f:
            return f.read()
